function myPromise (fun) {
  this.status = 'PENDING'

  this.result = null // 最终的结果
  this.success = [] // 成功的队列
  this.err = [] // 失败的队列

  this._resolve = res => {
    this.status = 'SUCCESS'
    this.result = res
    // 为了保证读取.then或者.catch 的回调函数在前，因为要保证先收集依赖
    setTimeout(() => {
      this.success.forEach(item => item(this.result))
    }, 0)
  }
  this._reject = err => {
    this.status = 'FAILED'
    this.result = err
    setTimeout(() => {
      this.err.forEach(item => item(this.result))
    }, 0)
  }
  
  if (Object.prototype.toString.call(fun) === '[object Function]') {
    fun(this._resolve, this._reject)
  } else {
    return console.log('Promise should 。。。。')
  }

}

myPromise.prototype.then = function (fn) {
  this.success.push(fn)
  return this
}

myPromise.prototype.catch = function (fn) {
  this.err.push(fn)
  return this
}


myPromise.prototype.all = function (arrPromise) {
  let result = []
  return new myPromise((resolve, reject) => {
    arrPromise.forEach(item => {
      item.then(
        res => {
          result.push(res)
        }
      )
      // 有一个 promise 执行失败，那么直接 reject
      .catch(err => {
        reject(err)
      })
    })
    resolve(result)
  })
}


var my_p = function () {
  return new myPromise((resolve, reject) => {
    // resolve(1)
    var xhr = new XMLHttpRequest()
    xhr.open('GET', 'https://jsonplaceholder.typicode.com/todos/1', true)
    xhr.onreadystatechange = () => {
      if (xhr.readyState === 4) {
        var status = xhr.status
        if (status >= 200) {
          resolve(JSON.parse(xhr.responseText))
        } else {
          reject(xhr.responseText)
        }
      } 
    }
    xhr.send(null)
  })
  
}
// 测试 promise
my_p()
  .then(res => console.log('res', res))
  .catch(err => console.log(err))



// 测试 Promise.all
myPromise.prototype.all([my_p(), my_p(), my_p()]).then((res) => {
  console.log(res)
})
.catch(err => {
  console.log('err return')
})